// pages/shoppingCar/shoppingCar.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts: [],               // 购物车列表
    hasList: false,          // 列表是否有数据
    totalPrice: 0.00,           // 总价，初始为0
    selectAllStatus: 0,    // 全选状态，默认全选
    show_title: true         //是否为编辑状态
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var sign = wx.getStorageSync("sign");
    wx.showLoading({
      title: '加载中',
    })

    wx.request({
      url: app.globalData.ydnBase + '/index.php/Weshop/SApi/index/m/cartIndex/key/2sdfdd332342341dddff46e189670/sign/' + sign +'/wid/39',
      method:"POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success:function(res){
        // console.log("购物车",res.data.datas);
        wx.hideLoading();
        if(res.data.status){
          var cateList = res.data.datas.cateList;
          var pic_domain = res.data.datas.pic_domain;
          that.setData({
            carts: cateList,
            hasList: true,
            pic_domain: pic_domain 
          })
          that.getTotalPrice();
        }
      }
    })
  },

  // 编辑购物车列表
  edit:function(){
    this.setData({
      show_title: false
    })
  },

  // 完成购物车列表
  editOver: function () {
    this.setData({
      show_title: true
    })
  },

  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    let total = 0;
    for (let i = 0; i < carts.length; i++) {        // 循环列表得到每个数据
      if (carts[i].selected == 1) {                   // 判断选中才会计算价格
        total += carts[i].goods_num * carts[i].goods_price;     // 所有价格加起来
      }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },


  selectList(e) {
    var that = this;
    var sign= wx.getStorageSync("sign");

    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    var num = e.currentTarget.dataset.num;
    var id = e.currentTarget.dataset.id;

    let carts = this.data.carts;                    // 获取购物车列表
    var selectAllStatus = this.data.selectAllStatus;
    
                 // 改变状态
    if (carts[index].selected == 1){
      carts[index].selected = 0;
    } else if (carts[index].selected == 0){
      carts[index].selected = 1;
    }

    wx.request({
      url: app.globalData.ydnBase + '/index.php/Weshop/SApi/index/m/updateCartCount/key/2sdfdd332342341dddff46e189670/wid/39/sign/' + sign,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        cart_id: id,
        goods_count: num,
        selected: carts[index].selected
      },
      success: function (res) {
        // console.log("完成", res);
        if (res.data.status) {
          that.setData({
            carts: carts,
            selectAllStatus: selectAllStatus
          });
        }
      }
    })

    this.getTotalPrice();                           // 重新获取总价
  },

  selectAll(e) {
    var that = this;
    let carts = this.data.carts;
    let selectAllStatus = this.data.selectAllStatus;    // 是否全选状态
    var sign = wx.getStorageSync("sign");

    var arr_cart = [];
    var arr_goods = [];
    var arr_select = [];

    if (selectAllStatus == 1){
      selectAllStatus = 0;
    }else{
      selectAllStatus = 1;
    }
    

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;            // 改变所有商品状态
      arr_cart.push(carts[i].id);
      arr_goods.push(carts[i].goods_num);
      arr_select.push(selectAllStatus); 
    }
    
    this.getTotalPrice();                               // 重新获取总价


    arr_cart = arr_cart.join();
    arr_goods = arr_goods.join();
    arr_select = arr_select.join();
    wx.request({
      url: app.globalData.ydnBase + '/index.php/Weshop/SApi/index/m/updateCartCount/key/2sdfdd332342341dddff46e189670/wid/39/sign/' + sign,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        cart_id: arr_cart,
        goods_count: arr_goods,
        selected: arr_select
      },
      success: function (res) {
        // console.log("完成", res);
        if (res.data.status) {
          that.setData({
            selectAllStatus: selectAllStatus,
            carts: carts
          });
        }
      }
    })
  },

  // 增加数量
  addCount(e) {
    var index = e.currentTarget.dataset.index;
    const store = e.currentTarget.dataset.store;
    var carts = this.data.carts;
    let num = Number(carts[index].goods_num);    

    num = num + 1;
    if(num <= store){
      carts[index].change = "true"; 
      carts[index].goods_num = num;
      this.setData({
        carts: carts
      });
      this.getTotalPrice();
    }else{
      wx.showToast({
        title: '库存不足',
      })
    }
    
  },
  // 减少数量
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = Number(carts[index].goods_num);
    if (num <= 1) {
      return false;
    }
    carts[index].change = "true"; 
    num = num - 1;
    carts[index].goods_num = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  // 删除某一列商品
  deleteList(e) {
    var that = this;
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;

    var id = e.currentTarget.dataset.id;
    var sign = wx.getStorageSync("sign");

    wx.showModal({
      title: '温馨提示',
      content: '是否确定删除此项',
      confirmText: "删除",
      success:function(res){
        if(res.confirm){
          wx.request({
            url: app.globalData.ydnBase + '/index.php/Weshop/SApi/index/m/deleteCart/key/2sdfdd332342341dddff46e189670/wid/39/sign/' + sign,
            method: "POST",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            data: {
              cart_id: id
            },
            success: function (res) {
              console.log("删除", res);
              if (res.data.status) {
                carts.splice(index, 1);              // 删除购物车列表里这个商品
                that.setData({
                  carts: carts
                });
                if (!carts.length) {                  // 如果购物车为空
                  that.setData({
                    hasList: false,
                    totalPrice: 0.00              // 修改标识为false，显示购物车为空页面
                  });
                } else {                              // 如果不为空
                  that.getTotalPrice();           // 重新计算总价格
                }
                wx.showToast({
                  title: '删除成功',
                })
              }

            }
          })
        }
      }
    })

   

    
  },

// 删除所有
  deleteAll:function(){
    var that = this;
    var carts = that.data.carts;
    var sign = wx.getStorageSync("sign");
    var arr_id = [];
    var str = '';
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].selected == 1) {
        arr_id.push(carts[i].id);
        str = arr_id.join();
      }
    }
    console.log("str",str);
    if(str != ""){
      wx.request({
        url: app.globalData.ydnBase + '/index.php/Weshop/SApi/index/m/deleteCart/key/2sdfdd332342341dddff46e189670/wid/39/sign/' + sign,
        data: {
          cart_id: str
        },
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log("删除", res);
          if (res.data.status == 1) {
            for (var i = 0; i < carts.length; i++) {
              if (carts[i].selected == 1) {
                carts.splice(i,1);
              }
            }
            that.getTotalPrice();
            this.setData({
              carts: carts,
              hasList: false
            });
            wx.showToast({
              title: '删除成功',
            })
          }
        }
      })
    }else{
      wx.showToast({
        title: '没有选中的商品',
      })
    }
    
  },

// 完成编辑，发送后台数据
  editOver:function(){
    var that = this;
    var arr_cart = [];
    var arr_goods = [];
    var arr_select = [];
    var carts = that.data.carts;
    var sign = wx.getStorageSync("sign");

    for(var i=0;i<carts.length;i++){
      console.log(carts[i]);
      if(carts[i].change == "true"){
        arr_cart.push(carts[i].id);
        arr_goods.push(carts[i].goods_num);
        arr_select.push(carts[i].selected); 
        console.log(arr_cart,arr_goods,arr_select);     
      }
    }
    if (arr_cart && arr_goods && arr_select){
      arr_cart = arr_cart.join();
      arr_goods = arr_goods.join();
      arr_select = arr_select.join();
      wx.request({
        url: app.globalData.ydnBase + '/index.php/Weshop/SApi/index/m/updateCartCount/key/2sdfdd332342341dddff46e189670/wid/39/sign/' + sign,
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          cart_id: arr_cart,
          goods_count: arr_goods,
          selected: arr_select
        },
        success: function (res) {
          console.log("完成", res);
          if (res.data.status) {
            wx.showToast({
              title: '修改成功',
            })
            that.setData({
              show_title: true
            })
          }
        }
      })
    }

  },

  // 支付
  payment: function(){
    var that = this;
    var arr = [];
    var carts = that.data.carts;
    for(var i=0;i<carts.length;i++){
      if(carts[i].selected == 1){
        wx.navigateTo({
          url: 'confirmOrder/confirmOrder',
        })
        return;
      }else{
        wx.showToast({
          title: '没有选中',
        })
      }
    }
   
  }
  
})